<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content='width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, shrink-to-fit=yes'>
    <title>健康生活 来个博世</title>
    <link rel="stylesheet" href="TemplateData/style.css">

    <style>
        html{
            height: -webkit-fill-available;
        }
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            min-height: -webkit-fill-available;
            width: 100vw;
            overflow: hidden;
        }
        .ctaDiv {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            background: #fffa;
            z-index: 99;
        }
        #bg {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            background-image: url('TemplateData/unity-logo-light.png'); /* 替换为你的背景图片路径 */
            background-size: cover;
            background-position: center top;
        }
        #bg2 {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 5.67px;
            z-index: -1;
            background-image: url('TemplateData/组 8@2x.png'); /* 替换为你的背景图片路径 */
            background-size: cover;
            background-position: center top;
        }
        #startARDiv {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: url('TemplateData/unity-logo-light.png'); /* 替换为你的背景图片路径 */
            background-size: cover;
            background-position: center top;
        }
        #tip {
            position: absolute;
            top: 31.5px;
            left:3.65%;
            width: 91.2%;
            height: 80%;
            background-image: url('TemplateData/文字组@3x.png'); /* 替换为你的背景图片路径 */
            background-size: contain;
            background-repeat: no-repeat;
            background-position: center top;
            pointer-events: none;
        }
        #startARButton_tip {
            position: absolute;
            top: 31.5px;
            left:3.65%;
            width: 91.2%;
            height: 80%;
            background-image: url('TemplateData/字体@3x.png'); /* 替换为你的背景图片路径 */
            background-size: contain;
            background-repeat: no-repeat;
            background-position: center top;
            pointer-events: none;
        }
        #startARButton {
            position: absolute;
            top: 86%;
            left: 51.5%;;
            width: 26.2%;
            height: 160px;
            transform: translateX(-50%);
            background:transparent;
            background-image: url('TemplateData/开始按钮@3x.png'); /* 替换为你的背景图片路径 */
            background-size: contain;
            background-repeat: no-repeat;
            background-position: center top;
            border: none; /* 去掉边框 */
            outline: none; /* 去掉焦点边框 */
            cursor: pointer; /* 鼠标悬停时显示手形指针 */
            padding: 0; /* 去掉内边距 */
            appearance: none; /* 去掉默认样式 */
            -webkit-appearance: none; /* 去掉默认样式（Webkit 浏览器） */
            -moz-appearance: none;
        }
        #custom-bar {
            position: absolute;
            top: 85%;
            left: 50%;
            transform: translateX(-50%);
            width: 70%; /* 居中显示，宽度为屏幕宽度的 90% */
            height: 70px; /* 高度 */
            border-radius: 5px;
            /* overflow: hidden; */
        }
        #custom-bar-empty {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%; /* 背景宽度 */
            height: 60px; /* 背景高度 */
            margin-top: 0px; /* 背景顶部边距 */
            background: url('TemplateData/progress-bar-empty-light.png');
            background-size: contain;
            background-repeat: no-repeat;
            background-position: center top;
        }
        #custom-bar-full {
            position: absolute;
            left: 13px;
            width: 0%; /* 初始填充宽度 */
            height: 10px; /* 填充高度 */
            margin-top: 3px; /* 背景顶部边距 */
            background: url('TemplateData/progress-bar-full-light.png');
            background-size: cover;
            background-repeat: no-repeat;
        }
    </style>
</head>
<body>
    <input type="hidden" id="imageUrl" value="">
    <div id="bg">
        <div id="bg2"></div>
        <div id="tip"></div>
        <div id="custom-bar">
            <div id="custom-bar-empty"></div>
            <div id="custom-bar-full"></div>
        </div>
    </div>
    <audio id="adCut" src="TemplateData/切3.MP3" preload="auto"></audio>
    <audio id="adTimer" src="TemplateData/倒计时音效.MP3" preload="auto"></audio>
    <audio id="clickSound" src="TemplateData/点击2.MP3" preload="auto"></audio>
    <video id="webcam-video" muted autoplay playsinline style="width:1px;position:absolute"></video>
    <canvas id="video-canvas" style="width:100%; height:100%; object-fit:cover; position:absolute"></canvas>
    <div id="startARDiv" class="ctaDiv">
        <div id="bg2"></div>
        <div id="startARButton_tip"></div>
        <button id="startARButton" onclick="StartAR()"> </button> 
        <select id="chooseCamSel" style="display: none;" onchange="SelectCam()"></select>
    </div>
    <div id="screenshotDiv" style="display: none;" class="ctaDiv">
        <div style="position:relative; background-color:white; padding:10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.3), 0 6px 20px 0 rgba(0, 0, 0, 0.25);">
            <img id="screenshotImg" src="" alt="screenshot" style="width:80vw; height:80vh">
            <button onclick="document.getElementById('screenshotDiv').style.display = 'none';" style="position:absolute; transform:translateY(-100%); right:0; top:0">Close</button>
        </div>
    </div>
    <div id="errorDiv" class="ctaDiv" style="display: none; background:#aaa">
        <p id="errorText" style="text-align: center; width:60vw; color:white"></p>
    </div>
    <div id="unity-container" class="unity-mobile">
        <canvas id="unity-canvas" style="width: 100%; height: 100%; background: #0000; z-index: -99;"></canvas>
        <!-- <div id="unity-loading-bar">
            <div id="unity-logo"></div>
            <div id="unity-progress-bar-empty">
                <div id="unity-progress-bar-full"></div>
            </div>
        </div> -->
        <canvas id="video-canvas"></canvas>
    </div>
    <script src="arcamera.js" type="text/javascript"></script>
    <script src="wtracker.js" type="text/javascript"></script>
    <script src="Build/{{{ LOADER_FILENAME }}}"></script>
    <script>
        var initialize = async() =>{
            var unityCanvas = document.querySelector("#unity-canvas");
            var videoCanvas = document.querySelector("#video-canvas");
            window.arCamera = new ARCamera(unityCanvas, videoCanvas);
            window.wTracker = new WorldTracker(arCamera);
            try{
                await wTracker.initialize("./opencv.js");
                console.log("World tracker initialized!");   
            }
            catch (error) {
                console.error("Failed to initialize world tracker. Are you missing opencv.js?", error);
                ShowError("初始化世界跟踪器失败.\n" + error);
                return;
            }

            await LoadWebcams();
            document.getElementById("startARButton").style.display = "block";
        }

        initialize();
        var btn = document.getElementById('clickSound');
        var cut = document.getElementById('adCut');
        var timer = document.getElementById('adTimer');
        function PlayBtn(){
            btn.play();
        }
        function PlayCut(){
            var audio = cut.cloneNode(true);
            document.body.appendChild(audio);
            audio.currentTime = 0.3;
            audio.play();
        }
        function PlayTimer(){
            timer.play();
        }
        function getQueryParameter(param) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(param);
        }

        function setImageUrlFromQuery() {
            const imageUrl = getQueryParameter('avatarUrl').replace('cms-pos.bshg.com.cn', 'static-omp.bshg.com.cn');
            if (imageUrl) {
                const fullImageUrl = `https://images.weserv.nl/?url=${encodeURIComponent(imageUrl)}`;
                document.getElementById('imageUrl').value = fullImageUrl;
                fetchAndConvertToBase64();
            } else {
                console.log("未提供图片URL");
            }
        }

        async function fetchAndConvertToBase64() {
            const imageUrl = document.getElementById('imageUrl').value;
            if (imageUrl) {
                try {
                    const response = await fetch(imageUrl);
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    const blob = await response.blob();
                    const reader = new FileReader();
                    reader.onloadend = function() {
                        const base64String = reader.result.split(',')[1]; // 去掉"data:image/jpeg;base64,"
                        console.log(base64String);
                        sendToUnity(base64String);
                    };
                    reader.readAsDataURL(blob);
                } catch (error) {
                    console.error("获取图片失败:", error);
                }
            } else {
                console.log("请输入图片URL");
            }
        }


        function sendToUnity(base64String) {
            // 假设你已经有一个方法可以与Unity通信
            // 例如，使用WebGL的Unity实例
            window.unityInstance.SendMessage('ImageReceiver', 'ReceiveImage', base64String);
        }


        var container = document.querySelector("#unity-container");
        var canvas = document.querySelector("#unity-canvas");
        // var loadingBar = document.querySelector("#unity-loading-bar");
        // var progressBarFull = document.querySelector("#unity-progress-bar-full");
        var loadingBar = document.querySelector("#custom-bar");
        var progressBarFull = document.querySelector("#custom-bar-full");
        function StartAR() {
            canvas.style.width = window.innerWidth + "px";
            canvas.style.height = window.innerHeight + "px";
            var audio = document.getElementById('clickSound');
            audio.play();
            document.getElementById('startARDiv').style.display = 'none';
            createUnityInstance(document.querySelector("#unity-canvas"), {
                    dataUrl: "Build/{{{ DATA_FILENAME }}}",
                    frameworkUrl: "Build/{{{ FRAMEWORK_FILENAME }}}",
                #if USE_WASM
                    codeUrl: "Build/{{{ CODE_FILENAME }}}",
                #endif
                #if MEMORY_FILENAME
                    memoryUrl: "Build/{{{ MEMORY_FILENAME }}}",
                #endif
                #if SYMBOLS_FILENAME
                    symbolsUrl: "Build/{{{ SYMBOLS_FILENAME }}}",
                #endif
                    streamingAssetsUrl: "StreamingAssets",
                    companyName: {{{ JSON.stringify(COMPANY_NAME) }}},
                    productName: {{{ JSON.stringify(PRODUCT_NAME) }}},
                    productVersion: {{{ JSON.stringify(PRODUCT_VERSION) }}},
                    //webglContextAttributes: { "preserveDrawingBuffer": true },
                    // matchWebGLToCanvasSize: false, // Uncomment this to separately control WebGL canvas render size and DOM element size.
                    // devicePixelRatio: 1, // Uncomment this to override low DPI rendering on high DPI displays.
                    },
                    (progress) => {
                        progressBarFull.style.width = 100 * progress + "%";
                    }
                ).then((unityInstance) => {
                window.unityInstance = unityInstance;
                RequestWebcam();
                loadingBar.style.display = "none";
                setImageUrlFromQuery();
            });
            StartMotionSensors();
            
            //Call Start GPS here --> StartGPS();

            
            
            loadingBar.style.display = "block";
        }
        //StartAR()
        //Set Facing Mode here ('environment', 'user', '')
        window.unityFacingMode = "environment";

        window.WEBCAM_SETTINGS = {
            video: {
                facingMode: unityFacingMode,
            },
            audio: false
        };
        window.requestingForCameraPermission = false;
        async function RequestWebcam(){
            print("RequestWebcam1")
            window.requestingForCameraPermission = true;
            try{
                print("RequestWebcam2")
                window.webcamStream = await navigator.mediaDevices.getUserMedia(window.WEBCAM_SETTINGS);
                arCamera.setFlipped(window.WEBCAM_SETTINGS.video.facingMode == 'user');
                
                console.log("Webcam access granted");
                requestingForCameraPermission = false;
            }
            catch (err) {
                //user denied camera permission - show error panel
                console.error("getUserMedia error - " , err);
                ShowError("未能启动体验。相机权限被拒绝");
                window.requestingForCameraPermission = false;
            }           
        }
        async function StartWebcam(){
            console.log("StartWebcam")

            while (window.requestingForCameraPermission) {
                // Wait until requestingForCameraPermission becomes true.
                console.log("Waiting for permissions...");
                await new Promise(resolve => setTimeout(resolve, 100)); // Adjust the delay time as needed.
            }

            console.log("Got Permissions");

            if(window.webcamStream)
            {
                const video = document.querySelector("#webcam-video");
                video.srcObject = webcamStream;
                try {
                    await arCamera.startWebcam(video);
                    console.log("Webcam started successfully");

                    window.unityInstance.SendMessage('ARCamera', 'OnStartWebcamSuccess');
                }
                catch(err){
                    console.error("Webcam failed to start - ", err);
                    window.unityInstance.SendMessage('ARCamera', 'OnStartWebcamFail');
                }   
            }
            else{
                console.error("Webcam failed to start - permission not yet granted");
                window.unityInstance.SendMessage('ARCamera', 'OnStartWebcamFail');
            }  
        }

        async function LoadWebcams(){
            let camDevices = [];
            let devices = await navigator.mediaDevices.enumerateDevices();
            var ctr = 0;
            devices.forEach(mediaDevice => {
                if (mediaDevice.kind === 'videoinput') {

                    if(window.unityFacingMode == 'environment' && !mediaDevice.label.includes('facing front')){
                        //back cam only
                        camDevices.push(mediaDevice);
                    }
                    else if(window.unityFacingMode == 'user' && mediaDevice.label.includes('facing front')){
                        //front cam only
                        camDevices.push(mediaDevice);
                    }
                    else{
                        //back and front
                        camDevices.push(mediaDevice);
                        console.log('pushed', mediaDevice);
                    }   
                    
                    ctr++;
                }
            });
            var select = document.getElementById("chooseCamSel");
            //select.style.display = "block";
            var count = 0;
            //reverse array because some Android phones can't distinguish front and back cams at first load
            //and when this happens, most of the time, front cam goes first and back cam goes last
            camDevices = camDevices.reverse();
            camDevices.forEach(mediaDevice => {
                const option = document.createElement('option');
                option.value = mediaDevice.deviceId;
                let label = `摄像头 ${count}`;
                if (mediaDevice.label) {
                    if(mediaDevice.label.includes('facing front')){
                        label = '后置摄像头';
                    }
                    else if(mediaDevice.label.includes('facing back')){
                        label = '前置摄像头';
                    }
                    else{
                        label = mediaDevice.label
                    }
                }
                const textNode = document.createTextNode(label);
                option.appendChild(textNode);
                select.appendChild(option);
                count++;
            });
            wTracker.WEBCAM_NAME = select.options[select.selectedIndex].innerHTML;
        }
        function SelectCam(){
            var select = document.getElementById("chooseCamSel");
            window.deviceId = select.value;
            window.WEBCAM_SETTINGS.video['deviceId'] = deviceId;
            //console.log(window.WEBCAM_SETTINGS);
            wTracker.WEBCAM_NAME = select.options[select.selectedIndex].innerHTML;
        }

        async function FlipCam(){
            arCamera.stopWebcam();
            window.WEBCAM_SETTINGS.video.deviceId = '';

            if(window.WEBCAM_SETTINGS.video.facingMode == 'user'){
                 window.WEBCAM_SETTINGS.video.facingMode = 'environment';
                arCamera.setFlipped(false);
            }
            else{
                window.WEBCAM_SETTINGS.video.facingMode = 'user';
                arCamera.setFlipped(true);
            }
            window.webcamStream = await navigator.mediaDevices.getUserMedia(window.WEBCAM_SETTINGS);

            const video = document.querySelector("#webcam-video");
            video.srcObject = webcamStream;

            await arCamera.startWebcam(video);
        }

        function StartMotionSensors(){
            window.wTracker.startAngles()
            .then(()=>{
                console.log("Motion sensors started");
            })
            .catch(error=>{
                console.error("Failed to start motion sensors - " + error);
                ShowError("未能启动体验. " + error);

            });
        }

        function StartGPS(){            
            window.wTracker.startGPS()
            .then((pos)=>{
                console.log("GPS started", pos);
            })
            .catch(error=>{
                console.error("Failed to start GPS - " + error);
                //ShowError("Failed to start GPS " + error);
            });
        }
        

        function ShowError(error){
            document.getElementById("errorDiv").style.display = "flex";
            document.getElementById("errorText").innerHTML = error;
        }

        function ShowScreenshot(dataUrl){
            document.getElementById("screenshotDiv").style.display = "flex";
            document.getElementById("screenshotImg").src = dataUrl;
            document.getElementById("screenshotImg").style.width = "80vw";
            document.getElementById("screenshotImg").style.height = 80 / window.innerWidth * window.innerHeight + "vw";
        }
        
    </script>
</body>
</html>
